package be.kuleuven.peno3.mobiletoledo.server;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

@Path ("/CredentialsHandler")
public class CredentialsServer {

	protected DatabaseManager manager = DatabaseManager.getInstance();

	@GET
	@Path ("/testCredentials")
	@Produces ("application/json")
	public String testCredentials(@QueryParam("userid") String userid, @QueryParam("password") String password){
		String query = "SELECT * FROM credentials";
	    query += " WHERE username='"+userid+"' AND password='"+password+"'";
	    
		String result = queryForCredentials(query);
		manager.disconnect();
		return result;
	}
	
	@SuppressWarnings("static-access")
	private String queryForCredentials(String query) {
		ResultSet rs = manager.query(query);
		Gson gson = new Gson();
		try {
			while(rs.next()) {
				JsonObject credentials = (JsonObject) gson.toJsonTree(manager.getColumnValues(rs));
				return credentials.get("teacher").getAsString();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		
		return "failed"; //niet ingelogd
	}
}
